
#########################################################################

# Copyright (C) Flavio Piccinelli 2012 <flavio.picci@gmail.com>

#########################################################################

# ariaCli.rb
# This file is part of "AriaAperta".

# AriaAperta is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# AriaAperta is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with AriaAperta.  If not, see <http://www.gnu.org/licenses/>.

#########################################################################
#########################################################################


#########################################################################
# Required libraries
#########################################################################
require "thread"
require "openssl"
require "socket"
require "lib/const"
require "lib/Utils"
#########################################################################

include Utils

module Aria

	class AriaCli

		attr_reader :req, :opts, :username, :passwd

		def initialize(req, opts=nil, username=nil, passwd=nil)
			if !req.nil?
				req = req
				if !(req == 0 || req == 1 || req == 2 || (req == 3 && !opts.nil?))
					Utils::usage
				end
			else
				Utils::usage
			end

			@req      = req
			@opts     = opts
			@username = username
			@passwd   = passwd
		end
	
		def main

			ret_var = 0

			socket = TCPSocket.new(SERVER, PORT)

			sslContext = OpenSSL::SSL::SSLContext.new
			sslContext.ca_file = "#{CERT_PATH}ca_cert.pem"
			sslContext.verify_mode = OpenSSL::SSL::VERIFY_PEER

			begin
				ssl = Utils::MySSLSocket.new(socket, sslContext)
				ssl.sync_close = true
				ssl.connect
			rescue => error
				ret_var = "error in socket: #{error}"
			end

			Utils::authenticate(ssl, @username, @passwd)

			ssl.puts req
			case req
			when 0
				ret_var = Utils::req_voip(ssl)
			when 1
				ret_var = Utils::req_vm(ssl)
			when 2
				ret_var = Utils::req_ack(ssl)
			when 3
				ret_var = Utils::req_close(ssl, @opts)
			end

			return ret_var

		ensure
			if !ssl.nil?
				ssl.close
			end
		end

	end

end